<?php
namespace app\system\controller;

use app\common\model\ShopExpressModel;
use think\Request;

class ShopExpressController extends BaseController
{

    private $shopExpressModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->shopExpressModel = new ShopExpressModel();
    }

    /**
     * 首页
     */
    public function index()
    {
        $map         = [];
        $query       = [];
        $expressName = $this->request->param('express_name');
        if (!empty($expressName)) {
            $map['express_name']   = ['like', '%' . $expressName . '%'];
            $query['express_name'] = $expressName;
        }
        $list = $this->shopExpressModel->where($map)->paginate(10, false, [
            'query' => $query,
        ]);
        $this->assign('list', $list);
        $this->assign('query', $query);
        return $this->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'ShopExpressValidate');
            if ($result !== true) {
                $this->error($result);
            }
            $this->shopExpressModel->addData($data);
            $this->updateCache();
            $this->success('添加成功', url('index'));
        }
        return $this->fetch();
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            $result = $this->validate($data, 'ShopExpressValidate');
            if ($result !== true) {
                $this->error($result);
            }
            $this->shopExpressModel->editData($data);
            $this->updateCache();
            $this->success('操作成功！', url('index'));
        }
        $expressId = $this->request->param('express_id');
        $info      = $this->shopExpressModel->where('express_id', $expressId)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            $expressId = $this->request->param('express_id/d');
            $this->shopExpressModel->delData($expressId);
            $this->updateCache();
            $this->success('删除成功！');
        }
    }

    public function updateCache()
    {
        $this->shopExpressModel->updateCache();
        $this->success('更新成功！', url('index'));
    }
}
